const appSecret: string = 'VJBqgTsiVmg';
const CryptoJS = require('crypto-js');

/**
 * 获取request签名
 * @param query 请求参数
 * @param url  请求地址
 * @returns
 */
export const getSign = (query: any, url: string) => {
  let urlPath: string = url
    .split('?')[0]
    .replace('https://gw.open.1688.com/openapi/', '');
  let arr = [];
  for (let key in query) {
    arr.push(`${key}${query[key]}`);
  }
  arr = arr.sort();

  urlPath = urlPath + arr.join('');

  let sign: string = CryptoJS.HmacSHA1(urlPath, appSecret);
  return sign;
};

const _charStr =
  'abacdefghjklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789';

function RandomIndex(min: number, max: number, i: number) {
  let index = Math.floor(Math.random() * (max - min + 1) + min),
    numStart = _charStr.length - 10;
  //如果字符串第一位是数字，则递归重新获取
  if (i == 0 && index >= numStart) {
    index = RandomIndex(min, max, i);
  }
  //返回最终索引值
  return index;
}

export function getRandomString(len: number) {
  let min = 0,
    max = _charStr.length - 1,
    _str = '';
  //判断是否指定长度，否则默认长度为15
  len = len || 15;
  //循环生成字符串
  for (var i = 0, index; i < len; i++) {
    index = RandomIndex(min, max, i);
    _str += _charStr[index];
  }
  return _str;
}

export function getUrlParam(urlStr, urlKey) {
  const url = new URL(urlStr); // 字符串转换成url格式
  const paramsStr = url.search.slice(1); // 获取'?'后面的参数字符串
  const paramsArr = paramsStr.split('&'); // 分割'&'字符 获得参数数组
  for (let i = 0; i < paramsArr.length; i++) {
    const tempArr = paramsArr[i].split('=');
    if (tempArr[0] === urlKey) {
      return tempArr[1];
    }
  }
}

export const group = (array = [], subGroupLength = 0) => {
  let index = 0;
  const newArray = [];
  while (index < array.length) {
    newArray.push(array.slice(index, (index += subGroupLength)));
  }
  return newArray;
};

export function fileToBuf(file, cb) {
  var fr = new FileReader();
  var filename = file.name;

  fr.readAsArrayBuffer(file);
  fr.addEventListener(
    'loadend',
    (e) => {
      var buf = e.target.result;
      cb(buf, filename);
    },
    false,
  );
}

export function bufToFile(buf, filename) {
  return new File([buf], filename);
}

export function bufToBlob(buf, mimeType = '') {
  return new Blob([buf], { type: mimeType });
}

export function blobToBuf(blob, cb) {
  var fr = new FileReader();
  var type = blob.type;

  fr.readAsArrayBuffer(blob);
  fr.addEventListener(
    'loadend',
    (e) => {
      var buf = e.target.result;
      cb(buf, type);
    },
    false,
  );
}

export function parseQueryParams(query: any, deleteArr: any) {
  let queryClone = { ...query };
  let pageNum = query.pageNum;
  let pageSize = query.pageSize;

  delete queryClone.pageNum;
  delete queryClone.pageSize;

  for (const key in queryClone) {
    if (Object.prototype.hasOwnProperty.call(queryClone, key)) {
      const element = queryClone[key];
      if (element === '') {
        deleteArr.push(key);
      }
    }
  }

  deleteArr.map((item: string) => {
    delete queryClone[item];
  });

  return { queryClone, pageNum, pageSize };
}
